#include <iostream>
#include <vector>
#include <string>

#include <cstdio>
#include <cstring>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>


#define ERR_EXIT(m) \
        do {\
            perror(m); \
            exit(EXIT_FAILURE); \
        } while(0)

using PollfdList = std::vector<pollfd>;

int main() {
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);

    int idlefd, listenfd, connfd;
    int on, nready;
    struct sockaddr_in srvAddr, peerAddr;
    socklen_t peerlen;
    struct pollfd pfd;
    PollfdList pollfds;
   
    

    listenfd = socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
    if (listenfd < 0)
        ERR_EXIT("socket");
    
    memset(&srvAddr, 0, sizeof(srvAddr));
    srvAddr.sin_family = AF_INET;
    srvAddr.sin_port = htons(8888);
    srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    on = 1;
    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
        ERR_EXIT("setsockopt");
    if (bind(listenfd, (sockaddr *)&srvAddr, sizeof(srvAddr)) < 0)
        ERR_EXIT("bind");
    if (listen(listenfd, SOMAXCONN) < 0)
        ERR_EXIT("listen");

    pfd.fd = listenfd;
    pfd.events = POLLIN;
    pollfds.push_back(pfd);

    while (true) {
        nready = poll(pollfds.data(), pollfds.size(), -1);
        if (nready == -1) {
            if (errno == EINTR)
                continue;
            ERR_EXIT("poll");
        }
        else if (nready == 0)
            continue;
        
        if (pollfds[0].revents & POLLIN) {
            peerlen = sizeof(peerAddr);
            connfd = ::accept4(listenfd, (sockaddr *)&peerAddr, &peerlen, SOCK_NONBLOCK | SOCK_CLOEXEC);

            if (connfd == -1) {
                if (errno == EMFILE) {
                    close(idlefd);
                    idlefd = accept(listenfd, NULL, NULL);
                    close(idlefd);
                    idlefd = open("/dev/null", O_RDONLY | O_CLOEXEC);
                    continue;
                }
                else 
                    ERR_EXIT("accept4");
            }

            pfd.fd = connfd;
            pfd.events = POLL_IN;
            pfd.revents = 0;
            pollfds.push_back(pfd);
            --nready;

            std::cout << "ip = " << inet_ntoa(peerAddr.sin_addr)
                      << " port = " << ntohs(peerAddr.sin_port) << std::endl;
            
            if (nready == 0)
                continue;
        }

        std::cout << "pollfds size: " << pollfds.size() << std::endl;
        std::cout << "nready fds: " << nready << std::endl;

        for (auto it = pollfds.begin() + 1; it != pollfds.end() && nready > 0; ++it) {
            if (it->revents & POLL_IN) {
                --nready;
                connfd = it->fd;
                char buf[1024] = {0};
                int ret = read(connfd, buf, 1024);
                if (ret == -1)
                    ERR_EXIT("read");
                if (ret == 0) {
                    std::cout << "client closed" << std::endl;
                    it = pollfds.erase(it);
                    --it;

                    close(connfd);
                    continue;
                }

                std::cout << buf << std::endl;
                write(connfd, buf, strlen(buf));
            }
        }
    }

    return 0;
}